package com.example.pan.ui.file

import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.asLiveData
import androidx.lifecycle.viewModelScope
import androidx.paging.PagingData
import androidx.paging.cachedIn
import com.example.pan.aria2.Aria2Repository
import com.example.pan.http.PanRepository
import com.example.pan.model.FileInfo
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.mapLatest
import kotlinx.coroutines.flow.onStart
import kotlinx.coroutines.flow.transformLatest
import kotlinx.coroutines.launch
import javax.inject.Inject

data class Params(
    val dir: String,
    val token: String
)

@HiltViewModel
class DriveFileViewModel @Inject constructor(
    private val panRepository: PanRepository,
    private val aria2Repository: Aria2Repository
) : ViewModel() {

    private val dirStateFlow = MutableStateFlow("/")
    private val tokenStateFlow = MutableStateFlow("")

    @ExperimentalCoroutinesApi
    val fileInfoList: Flow<PagingData<FileInfo>> = dirStateFlow.mapLatest {
        it
    }.combine(tokenStateFlow) { f1, f2 ->
        Params(f1, f2)
    }.transformLatest {
        panRepository.list(it.dir, it.token).cachedIn(viewModelScope)
    }

    fun listFile(token: String, dir: String) =
        panRepository.list(dir, token).cachedIn(viewModelScope)

    private val dirs = arrayListOf<String>()

    fun changeDir(dir: String) {
        dirs.add(dir)
        dirStateFlow.value = dir
    }

    fun onBackDir() {
        dirs.removeLastOrNull()
        dirStateFlow.value = if (dirs.isEmpty()) {
            "/"
        } else {
            dirs.lastOrNull()
        }.toString()
    }

    fun initData(token: String) {
        dirs.clear()
        tokenStateFlow.value = token
    }

    @ExperimentalCoroutinesApi
    fun filemetas(fs_id: Long) = panRepository.filemeta(fs_id).asLiveData()


    @ExperimentalCoroutinesApi
    fun download(url: String, fileName: String) {
        viewModelScope.launch {
            aria2Repository.addUri(url, fileName).onStart {
                Log.e("addUri", "下载开始")
            }.catch {
                it.message?.let { it1 -> Log.e("addUri", it1) }
            }.collect {

            }
        }
    }

}